﻿using OA.BLL;

using OA.Core;
using OA.Model;
using OA.Model.View;
using Newtonsoft.Json;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using Microsoft.Extensions.Caching.Memory;
using OA.Web.Code;
using Microsoft.AspNetCore.Http;
using OA.Web.Attribute;
using Microsoft.AspNetCore.Mvc;
using OA.Model.DB;
using X.PagedList;
using OA.Model.Form;
using OA.Core.Helper;
using OA.Core.EF;

namespace OA.Web.Areas.Member.Controllers
{
    public class UserCenterController : BaseMemberController
    {
        private IMemoryCache _cache;
        private ICookie _cookie;
        public UserCenterController(ICookie cookie, IHttpContextAccessor accessor, IMemoryCache cache) : base(accessor, cookie, cache)
        {
            _cache = cache;
            _cookie = cookie;
        }
        /// <summary>
        /// 我的待办
        /// </summary>
        /// <returns></returns>
        [MyActionFilterAttribute("001001", "我的待办","个人中心",true, "icondaiban1")]
        public IActionResult WaitForHandling(string keyWord, int p = 1,int size=20)
        {            
            return View();
        }

        [MyActionFilterAttribute("001001", "我的待办")]
        public IActionResult GetWaitForHandlingData(string keyWord, int page = 1, int limit = 20)
        {
            ViewBag.KeyWord = keyWord;
            string empID = base.EmpID;
            Expression<Func<VWaitForHandling, bool>> where = m => m.RealEmpID == empID && m.Status == 0;
            if (!string.IsNullOrWhiteSpace(keyWord))
            {
                where = where.AndAlso<VWaitForHandling>(m => m.Title.Contains(keyWord));
            }
            var list = this.dbContextFactory.DbContext.VWaitForHandling.Where(where).OrderByDescending(m => m.ID).ToPagedList(page, limit);
            var result = new
            {
                code = "0",
                msg = "",
                count = list.TotalItemCount,
                data = list
            };
            return Json(result);

        }

        /// <summary>
        /// 我的已办
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        [MyActionFilterAttribute("001002", "我的已办", "个人中心", true, "iconzhuanzheng")]
        public IActionResult HaveDone()
        {            
            return View();
        }

        [MyActionFilterAttribute("001002", "我的已办")]
        public IActionResult GetHaveDoneData(string keyWord, int page = 1, int limit = 20)
        {
            
            string currentTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            Expression<Func<VHaveDone, bool>> where = m => m.RealEmpID == this.EmpID;
            if (!string.IsNullOrWhiteSpace(keyWord))
            {
                where = where.AndAlso<VHaveDone>(m => m.Title.Contains(keyWord));
            }

            var list = this.dbContextFactory.DbContext.VHaveDone.Where(where).OrderByDescending(m => m.ID).ToPagedList(page, limit);
            var result = new
            {
                code = "0",
                msg = "",
                count = list.TotalItemCount,
                data = list
            };
            return Json(result);
        }

        /// <summary>
        /// 我的发起
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        [MyActionFilterAttribute("001003", "我的主办", "个人中心", true, "iconzhubanquan")]
        public IActionResult Launched()
        {
            return View();
        }

        [MyActionFilterAttribute("001003", "我的主办")]
        public IActionResult GetLaunchedData(string keyWord, int page = 1, int limit = 20)
        {
             
            Expression<Func<VLaunched, bool>> where = m => m.SponsorEmpID == Info.EmpID && m.Status >= 1;
            if (!string.IsNullOrWhiteSpace(keyWord))
            {
                where = where.AndAlso<VLaunched>(m => m.Title.Contains(keyWord));
            }
            var list = this.dbContextFactory.DbContext.VLaunched.Where(where).OrderBy(m => m.ID).ToPagedList(page, limit);
            var result = new
            {
                code = "0",
                msg = "",
                count = list.TotalItemCount,
                data = list
            };
            return Json(result);
        }



        [HttpGet]        
        public IActionResult UpdatePassword()
        {
            return View(new UpdatePasswordForm());
        }

        [HttpPost]
        public IActionResult UpdatePassword(UpdatePasswordForm model)
        {
            if (model.NewPassWord != model.NewPassWord2)
            {
                ViewBag.Msg = "新密码与确认密码不一致!";
                return View();
            }
            Employee infoUser = this.GetInfo<Employee>(this.Info.ID);
            if (infoUser == null)
            {
                ViewBag.Msg = "非法的操作!";
                return View();
            }
            string md5PassWord = (infoUser.EmpID+ model.OldPassword).ToMd5String();
            if (infoUser.Password != md5PassWord)
            {
                ViewBag.Msg = "原始密码错误!";
                return View();
            }
            string md5PassWord2 = (infoUser.EmpID + model.NewPassWord).ToMd5String();
            Employee updateUser = new Employee();
            updateUser.Password = md5PassWord2;
            this.Update<Employee>(infoUser, updateUser, new string[] { "Password" });
            return FinshOther("密码更新成功");
        }

     

        /// <summary>
        /// 单据转移
        /// </summary>
        /// <param name="id"></param>
        /// <param name="empID"></param>
        /// <param name="explain"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Remove(int id, string empID, string explain)
        {
            BaseResult result = new BaseResult();
            //ApprovalItem item = this.dbContextFactory.DbContext.ApprovalItem.Where(m => m.ID == id).FirstOrDefault();
            //if (item == null || item.RealEmpID != Info.EmpID)
            //{
            //    result.State = 400;
            //    result.Msg = "没有找到审批项";
            //    return Json(result);
            //}
            //if (item.Status != 0)
            //{
            //    result.State = 400;
            //    result.Msg = "已经审批的单据不能重复审批";
            //    return Json(result);
            //}
            //Approval infoApproval = this.dbContextFactory.DbContext.Approval.Where(m => m.ID == item.ApprovalID).FirstOrDefault();
            //if (infoApproval == null)
            //{
            //    result.State = 400;
            //    result.Msg = "没有找到原始单据";
            //    return Json(result);
            //}
            //List<Approval> listApproval = this.dbContextFactory.DbContext.Approval.Where(m => m.VoucherID == infoApproval.VoucherID && m.TypeID == 1).ToList();
            //Approval nextApproval = listApproval.Where(m => m.EmpID == empID).FirstOrDefault();
            //if (nextApproval == null)
            //{
            //    result.State = 400;
            //    result.Msg = "没有找到新的审批人";
            //    return Json(result);
            //}

            //Approval updateApproval = new Approval();
            //updateApproval.Status = 7;
            //updateApproval.ApprovalTime = DateTime.Now;
            //updateApproval.Explain = explain;

            //Approval newApproval = JsonHelper.DeserializeObj<Approval>(JsonConvert.SerializeObject(nextApproval));
            //newApproval.ID = 0;
            //newApproval.Status = 0;
            //newApproval.Explain = "";

            //Voucher updateVoucher = new Voucher();
            //updateVoucher.CurrentApprover = newApproval.EmpName;

            //using (var trn = this.dbContextFactory.DbContext.Database.BeginTransaction())
            //{
            //    try
            //    {
            //        this.dbContextFactory.AddInfo<Approval>(newApproval);
            //        this.dbContextFactory.Update<Approval>(infoApproval, updateApproval, new string[] { "Status", "ApprovalTime", "Explain" });
            //        this.dbContextFactory.Update<Voucher>(infoVoucher, updateVoucher, new string[] { "CurrentApprover" });
            //        trn.Commit();
            //        return Json(result);
            //    }
            //    catch (Exception ex)
            //    {
            //        trn.Rollback();
            //        result.State = 400;
            //        result.Msg = "数据库操作异常!请联系管理员";
            //        return Json(result);
            //    }
            //}
            return Json(result);
        }


        [HttpGet]
        public IActionResult ChangeHead()
        {
            ViewBag.Avatar = Info.Pic + "?x-oss-process=image/resize,m_fill,w_200,h_200,limit_0/auto-orient,0/quality,q_90";
            return View();
        }


        [HttpGet]
        public IActionResult UpdateHead(string url)
        {
            try
            {
                Employee updateEmployee = new Employee { Pic = url };
                this.UpdateByID<Employee>(Info.ID, updateEmployee, new string[] { "Pic" });
                _cookie.SetCookies(CookieHelper.Avatar_User, url, 1440);
               
                return Json(new { State = 200, Message = "" });
            }
            catch (Exception ex)
            {
                return Json(new { State = 400, Message = "头像上传失败" });
            }

        }

        [HttpGet]
        public IActionResult Logout()
        {
            _cookie.DeleteCookies(CookieHelper.UserID);
            _cookie.DeleteCookies(CookieHelper.Avatar_User);
            return Redirect("/");
        }
    }
}